package com.sz.common.base.i18n.impl;

import com.sz.common.base.i18n.I18nMessages;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

/**
 * Function: I18nMessagesImpl <br>
 * Author: Charles <br>
 * Date: 2016-12-07 17:03:00
 */
@Service
public class I18nMessagesImpl implements I18nMessages {

    private static final String MESSAGE_NOT_FOUND = "<message not found>";

    @Autowired
    private MessageSource messageSource;

    @Override
    public String getMessage(String key, Object[] params, String defaultMessage) {
        return messageSource.getMessage(key, params, defaultMessage, LocaleContextHolder.getLocale());
    }

    @Override
    public String getMessage(String key, Object[] params) {
        try {
            return messageSource.getMessage(key, params, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException ex) {
            return MESSAGE_NOT_FOUND;
        }
    }

    @Override
    public String getMessage(MessageSourceResolvable resolver) {
        try {
            return messageSource.getMessage(resolver, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException ex) {
            return MESSAGE_NOT_FOUND;
        }
    }
}
